package com.test.mchelepesa.activity_fragment_rice.info_rice;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.camera.core.AspectRatio;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.exifinterface.media.ExifInterface;

import com.bumptech.glide.Glide;
import com.google.common.util.concurrent.ListenableFuture;
import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseInfoActivity_rice;
import com.test.mchelepesa.constant_rice.Constant_rice;
import com.test.mchelepesa.util_rice.PermissionUtil_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;
import com.test.mchelepesa.util_rice.imageUtil_rice.ImageConvert_rice;
import com.test.mchelepesa.view_rice.widget_rice.TitleView_rice;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class FaceInfoActivity_rice extends BaseInfoActivity_rice {

    private PreviewView previewView;
    private View photographView;
    private ImageButton photoIb;

    private Runnable runnableWithCameraPermission = null;

    private ListenableFuture<ProcessCameraProvider> listenableFuture;
    private ImageCapture imageCapture;
    private Bitmap faceBm;

    private String faceImgLocalUrl;

    private String faceImgUrl;

    private long startTime=0;

    private boolean deleteData = true;

    private View retakeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_info_rice);

        TitleView_rice titleView = findViewById(R.id.face_title);
        titleView.getBackIb().setOnClickListener(v -> onBackPressed());

        initLicense(
                findViewById(R.id.face_view_license),
                findViewById(R.id.face_license_logo),
                findViewById(R.id.face_license_company_name)
        );

        previewView = findViewById(R.id.face_preview);
        photographView = findViewById(R.id.face_view_photograph);
        photoIb = findViewById(R.id.face_ib_image);

        retakeView = findViewById(R.id.face_view_retake);

        View deleteDataView = findViewById(R.id.face_view_delete_data);
        ImageView deleteDataIv = findViewById(R.id.face_iv_delete_data);

        deleteDataView.setOnClickListener(v -> {
            deleteData = !deleteData;
            if (deleteData){
                deleteDataView.setBackgroundResource(R.drawable.ic_border_orange_rice_1dp_round_corner_white_10dp);
                deleteDataIv.setBackgroundResource(R.drawable.icon_select);
            }else {
                deleteDataView.setBackgroundResource(R.drawable.bg_white_round_corner_10);
                deleteDataIv.setBackgroundResource(R.drawable.icon_unselect);
            }
        });

        photoIb.setOnClickListener(v -> {

            HttpManager_rice.getInstance().saveUserBuriedPoint("FACE_START_TAKING_CLICK","");

            runnWithCameraPermission(this::startPhotograph);
        });

        retakeView.setOnClickListener(view -> {
            HttpManager_rice.getInstance().saveUserBuriedPoint("FACE_RETAKE_CLICK","");
            runnWithCameraPermission(this::startPhotograph);
        });

        photographView.setOnClickListener(v -> runnWithCameraPermission(() -> {

            if (!TextUtils.isEmpty(faceImgLocalUrl)){
                HttpManager_rice.getInstance().saveUserBuriedPoint("FACE_START_TAKING_CLICK",String.valueOf(System.currentTimeMillis()-startTime));
                startPhotograph();
            }else {
                try {
                    HttpManager_rice.getInstance().saveUserBuriedPoint("FACE_TAKE_PICTURE_CLICK","");
                    faceImgLocalUrl = imageFilePath();

                    ImageCapture.Metadata metadata = new ImageCapture.Metadata();
                    metadata.setReversedHorizontal(true);

                    ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(new File(faceImgLocalUrl))
                            .setMetadata(metadata)
                            .build();

                    imageCapture.takePicture(
                            //指定照片保存的位置和格式
                            options,
                            //指定保存照片时要运行的线程
                            ContextCompat.getMainExecutor(this),
                            //指定保存照片完成后的回调函数
                            new ImageCapture.OnImageSavedCallback() {
                                @Override
                                public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                                    try {

                                        Uri imgUri = outputFileResults.getSavedUri();

                                        if (imgUri!=null){
                                            faceImgLocalUrl = imgUri.getPath();

                                            Glide.with(FaceInfoActivity_rice.this).load(faceImgLocalUrl).into(photoIb);
                                            retakeView.setVisibility(VISIBLE);
                                            previewView.setVisibility(GONE);

                                            faceBm = BitmapFactory.decodeFile(faceImgLocalUrl);

                                            if (!TextUtils.isEmpty(faceImgLocalUrl)) {
                                                //照片压缩
                                                ImageConvert_rice.startConvertImage(
                                                        new File(faceImgLocalUrl),
                                                        (localPath, thumpImg) -> {
                                                            faceBm = thumpImg;
                                                            //上传照片
                                                            new Thread(() -> HttpManager_rice.getInstance().uploadImage(localPath)).start();
                                                        }
                                                );

                                            } else {
                                                faceImgLocalUrl = null;
                                                showToast_rice(getString(R.string.photo_upload_again_tip));
                                            }


                                        }

                                    } catch (Exception e) {
                                        StringUtil_rice.printException(e);
                                    }
                                }
                                @Override
                                public void onError(@NonNull ImageCaptureException exception) {
                                    Log.e("Sefie_Info", "Save Fail" );
                                }
                            }
                    );
                }catch (Exception e){
                    StringUtil_rice.printException(e);
                }
            }
        }));

        findViewById(R.id.face_btn_next).setOnClickListener(v -> {

            if (TextUtils.isEmpty(faceImgLocalUrl)){
                HttpManager_rice.getInstance().saveUserBuriedPoint("FACE_START_TAKING_CLICK","");
                runnWithCameraPermission(this::startPhotograph);
            }else {
                HttpManager_rice.getInstance().saveUserBuriedPointAndUpload("FACE_SAVE_CLICK","");
                HttpManager_rice.getInstance().uploadSefieInfo(StringUtil_rice.getSafeString(faceImgUrl),deleteData);
            }

        });

    }

    public void onImageUploadSuccess(String url){

        runOnUiThread(() -> {
            if (TextUtils.isEmpty(url)) {
                Toast.makeText(this, getString(R.string.photo_upload_again_tip),Toast.LENGTH_SHORT).show();
                return;
            }
            faceImgUrl = url;
        });
    }

    private void runnWithCameraPermission(Runnable runnable){
        if (PermissionUtil_rice.checkLaunchPermissions(this, Manifest.permission.CAMERA)){
            if (runnable!=null) runnable.run();
        }else {
            this.runnableWithCameraPermission = runnable;
            EasyPermissions.requestPermissions(this,getString(R.string.request_camera_permission),PermissionUtil_rice.REQ_CODE_PERMISSIONS_CAMERA,Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PermissionUtil_rice.REQ_CODE_PERMISSIONS_CAMERA && runnableWithCameraPermission!=null){
            HttpManager_rice.getInstance().saveUserBuriedPoint("FACE_CAMERA_PERMISSION_AGREE_CLICK","");
            runnableWithCameraPermission.run();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms) && requestCode == PermissionUtil_rice.REQ_CODE_PERMISSIONS_CAMERA){
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        if (requestCode == PermissionUtil_rice.REQ_CODE_PERMISSIONS_CAMERA){
            EasyPermissions.requestPermissions(this,getString(R.string.request_camera_permission),PermissionUtil_rice.REQ_CODE_PERMISSIONS_CAMERA,Manifest.permission.CAMERA);
        }
    }

    private String imageFilePath() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = sandboxFolderPath();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    private String sandboxFolderPath() {
        String inAppFolder = getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += Constant_rice.PRODUCT;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

    private void startPhotograph(){
        try {

            //点击图像隐藏,拍照按键显示
            photoIb.setImageBitmap(null);
            retakeView.setVisibility(GONE);
            photographView.setVisibility(VISIBLE);
            previewView.setVisibility(VISIBLE);

            startTime = System.currentTimeMillis();
            faceImgUrl = "";
            faceImgLocalUrl = "";

            //打开拍照
            listenableFuture = ProcessCameraProvider.getInstance(this);
            listenableFuture.addListener(() -> {
                try {
                    ProcessCameraProvider cameraProvider = listenableFuture.get();
                    Preview preview = new Preview.Builder()
                            .setTargetAspectRatio(AspectRatio.RATIO_4_3)
                            .build();
                    preview.setSurfaceProvider(previewView.getSurfaceProvider());
                    imageCapture = new ImageCapture.Builder().build();

                    //打开前置摄像头
                    CameraSelector cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA;
                    try {
                        cameraProvider.unbindAll();
                        cameraProvider.bindToLifecycle(FaceInfoActivity_rice.this, cameraSelector, preview,imageCapture);
                    } catch(Exception ignored) {

                    }
                } catch (ExecutionException | InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }, ContextCompat.getMainExecutor(this));
        }catch (Exception e){
            StringUtil_rice.printException(e);
        }
    }

    private void setExifOrientation(String filePath, int rotationDegrees) {
        try {
            ExifInterface exif = new ExifInterface(filePath);
            int orientation = ExifInterface.ORIENTATION_UNDEFINED;

            orientation = switch (rotationDegrees) {
                case 0 -> ExifInterface.ORIENTATION_NORMAL;
                case 90 -> ExifInterface.ORIENTATION_ROTATE_90;
                case 180 -> ExifInterface.ORIENTATION_ROTATE_180;
                case 270 -> ExifInterface.ORIENTATION_ROTATE_270;
                default -> orientation;
            };
            exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation));
            exif.saveAttributes();
        } catch (IOException e) {
            StringUtil_rice.printException(e);
        }
    }

    private int getRotationDegrees(int rotation) {
        return switch (rotation) {
            case Surface.ROTATION_0 -> 0;
            case Surface.ROTATION_90 -> 90;
            case Surface.ROTATION_180 -> 180;
            case Surface.ROTATION_270 -> 270;
            default -> 0;
        };
    }

}